/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Navbar,
    Toolbar,
    Text,
    Button,
    IconButton,
    MenuList,
    MenuItem,
    useTheme,
    useToast,
    LayerLoading,
    Container,
    IconMoreVertical,
    IconArrowLeft,
    IconArrowRight,
    IconRefButton,
    AlertDialog,
    IconCloud,
    IconPackage,
    TwoHalfRightPanel,
    VerticalMenu,
    DdMenuItem,
} from "customize-easy-ui-component";

import { Link as RouterLink } from "../../routing/Link";
import {ContainLine, TransparentInput} from "../../comp/base";
import {PreloadedQuery, usePreloadedQuery} from "react-relay/hooks";
import {ReportOverviewQuery} from "./__generated__/ReportOverviewQuery.graphql";
import {reportStatusMap} from "../../task/DeviceListItem";
import useDispatchToLiablerMutation from "../../task/useDispatchToLiablerMutation";
import useFillEqpFieldMutation from "./useFillEqpFieldMutation";
//import { useCommitOriginalData, useQueryOriginalRecord } from "../report/db";
const graphql = require("babel-plugin-relay/macro");
//[HOOK限制]按钮点击函数内部直接上toast()或toaster.notify()很可能无法正常显示。而放在函数组件顶层render代码前却能正常。

//const log = debug("app:Compose");

export interface ReportOverviewProps {
    prepared: {
        query: PreloadedQuery<ReportOverviewQuery>;
    }
    routeData: any;
}

export const ReportOverview = (props: ReportOverviewProps )=> {
  //const toast = useToast();
 // const [editing, setEditing] = React.useState(!readOnly);
  /*const [content, ] = React.useState(() => {
    return defaultDescription
      ? ''
      : null;
  });*/
  //const [image, ] = React.useState(defaultImage);
 // const [title, setTitle] = React.useState(defaultTitle);
  //const [credit, ] = React.useState(defaultCredit);

  const data = usePreloadedQuery<ReportOverviewQuery>(
      graphql`
        query ReportOverviewQuery($id: ID!) {
          getReport(id: $id) {
            id,type,upLoadDate,path,modeltype,modelversion,isp{
              id,no,nextIspDate,conclusion,dev{
                id,cod,oid,type,
              },bus{id,ident, task{
                id,date,status
              }}
            },
            stm{id,sta,master{id,person{id,name}},reviewer{id,person{id,name}},approver{id,person{id,name}},authr{id,person{id,name}}}
          }
        }
      `,
      props.prepared.query,
  );
  const { getReport:rep }=data;
    const theme = useTheme();
    let filtercomp={
        id: props.routeData.params.repId,
    };
 // const {error, loading, items:rep, } = useReport(filtercomp);
 //  const [ingredients, setIngredients] = React.useState<any>( rep||{} );

/*  React.useEffect(() => {
    setIngredients( rep||{} );
  }, [rep]);*/
    const {call:fillEqpFieldFunc,doing:doingfill, result:resfill}= useFillEqpFieldMutation();
    const [show, setShow] = React.useState(false);

  return (
    <TwoHalfRightPanel
          title={`报告ID号：${props.routeData.params.repId}`}
          back={
             <RouterLink href="/inspect">
                    <IconButton noBind icon={<IconArrowLeft/>}
                          variant="ghost"
                          label="后退"
                          size="md"
                          css={{
                              marginRight: theme.spaces.sm,
                              [theme.mediaQueries.md]: {
                                  display: "none"
                              }
                          }}/>
             </RouterLink>
            }
          menu={
              <VerticalMenu>
                  <DdMenuItem label="功能待续" onClick={(e) => {
                  }}/>
              </VerticalMenu>
          }
          divStyle={{
              margin: `${theme.spaces.sm} ${theme.spaces.sm}`
          }}
      >

      {rep && (
          <React.Fragment>

             <FirstPage id={props.routeData.params.ispId} rep={rep}/>
             <div css={{
                 display: 'flex',
                 flexWrap: 'wrap',
                 justifyContent: 'center',
                 alignItems: 'center',
                 lineHeight: '3rem',
              } }>
              <Button size="md" intent="primary" onPress={() => setShow(true)}>
                  基础信息赋值
              </Button>
              <RouterLink href={`/report/${rep.modeltype}/ver/${rep.modelversion}/${props.routeData.params.repId}/ALL`}>
                  <Button
                      noBind
                      intent="primary"
                      iconAfter={<IconArrowRight/>}
                  >
                   报告编制
                  </Button>
              </RouterLink>
              <RouterLink
                  href={`/inspect/${props.routeData.params.ispId}/report/${props.routeData.params.repId}/copy`}>
                  <Button noBind
                          intent="primary"
                          iconAfter={<IconArrowRight/>}
                  >
                      拷贝原始记录
                  </Button>
              </RouterLink>
              <RouterLink href={`/task/${rep?.isp?.bus?.task?.id}/detail/${props.routeData.params.ispId}/fee`}>
                  <Button noBind
                          intent="primary"
                          iconAfter={<IconArrowRight/>}
                  >
                      收费情况
                  </Button>
              </RouterLink>
              <RouterLink href={`/device/${rep?.isp?.dev?.id}`}>
                  <Button noBind
                     intent="primary"     iconAfter={<IconArrowRight/>}
                  >去设备台账
                  </Button>
              </RouterLink>
             </div>
          </React.Fragment>
      )}

      <AlertDialog
          isOpen={show}
          confirmLabel="是的，行动"
          subtitle="把旧的设备信息覆盖掉，主报告才有此功能，分项报此内容采信主报告的"
          title={"提取最新的台账信息给这份报告?"}
          onConfirm={() => {
              fillEqpFieldFunc(props.routeData.params.ispId);
              //原始方式的 window.alert("DELETE");
          }}
          onClose={() => {
              setShow(false);
          }}
      />
    </TwoHalfRightPanel>
  );
};



const FirstPage= ( {theme=null, id ,rep}: any
) => {
    const [ingredients, setIngredients] = React.useState<any>( rep||{} );
    //多人：检验员。
    const ispmennames = rep?.stm?.authr?.reduce(function(prev:any, cur:any, index: number, arr: any[]) {
                            return (prev? prev +';' :'') + cur.person?.name;
                        },null);

    return <React.Fragment>
              <Text variant="h5">该份报告的概要信息</Text>
              <ContainLine display={`报告号`}>
                  <Text>
                      {rep?.isp.no ||''}
                  </Text>
              </ContainLine>
              <ContainLine display={'设备号'}>
                  <Text>
                      {rep?.isp.dev?.cod || rep?.isp.bus.ident}
                  </Text>
              </ContainLine>
                <ContainLine display={'任务日期'}>
                        {rep?.isp?.bus?.task?.date || ''}
                </ContainLine>
              <ContainLine display={'报告类型'}>
                  <Text>
                      { (rep && rep.type) || ''}
                  </Text>
              </ContainLine>
              <ContainLine display={'整体报告检验结论'}>
                  <Text>
                      {rep?.isp?.conclusion ||''}
                  </Text>
              </ContainLine>
              <ContainLine display={'设备监察识别码'}>
                  <Text>
                      {rep?.isp.dev?.oid}
                  </Text>
              </ContainLine>
              <ContainLine display={'报告编制上传日期'}>
                  <Text>
                      {rep?.upLoadDate || ''}
                  </Text>
              </ContainLine>
              <ContainLine display={'设备安装地址'}>
                  <Text>
                      {(rep && rep.isp.dev?.pos && rep.isp.dev?.pos.address) ||''}
                  </Text>
              </ContainLine>
                <ContainLine display={'责任工程师'}>
                    <Text>
                        {rep?.stm?.reviewer?.person?.name||''}
                    </Text>
                </ContainLine>
                <ContainLine display={'审批人'}>
                    <Text>
                        {rep?.stm?.approver?.person?.name||''}
                    </Text>
                </ContainLine>
                <ContainLine display={'校核人：'}>
                        {rep?.stm?.master?.person?.name||''}
                </ContainLine>
                <ContainLine display={'检验员(多人)：'}>
                        {ispmennames||''}
                </ContainLine>
                <ContainLine display={'流程状态'}>
                    <Text>
                        {reportStatusMap.get(rep?.stm?.sta!) ||''}
                    </Text>
                </ContainLine>
  </React.Fragment>;
};

export default ReportOverview;
